package com.goddess.yeecolor.activity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.goddess.yeecolor.R;
import com.goddess.yeecolor.adapter.ExerciseFragmentPagerAdapter;
import com.goddess.yeecolor.base.BaseActivity;
import com.goddess.yeecolor.fragment.ExerciseitemFragment.ExerciseItem_activityArrange;
import com.goddess.yeecolor.fragment.ExerciseitemFragment.ExerciseItem_activityCommit;
import com.goddess.yeecolor.fragment.ExerciseitemFragment.ExerciseItem_activityDetails;
import com.goddess.yeecolor.tools.JumpIntents;
import com.goddess.yeecolor.tools.MyUrl;
import com.goddess.yeecolor.tools.OkttpUtils;
import com.goddess.yeecolor.tools.SharePreceUtils;
import com.goddess.yeecolor.tools.ToastUtils;
import com.goddess.yeecolor.view.Item_ExerciseItemButtom;
import com.goddess.yeecolor.view.MyBanner;
import com.goddess.yeecolor.view.NoScrollViewPager;
import com.goddess.yeecolor.view.PopPopuWindowUtils;
import com.goddess.yeecolor.view.dialog_progress;
import com.goddess.yeecolor.view.sharePopuWindow;
import com.youth.banner.Banner;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.sharesdk.framework.ShareSDK;

/**
 *活动详情的不同类型
 */
public class ExerciseItem2Activit extends BaseActivity {
    private SwipeRefreshLayout swipeRefreshLayout;
    private AppBarLayout app_bar2;
    private double price;
    private PopPopuWindowUtils popuWindowUtils;
    private String webview;
    private int islike,isapply;//判断底部收藏 购买
    private JSONArray activity,workers;
    private ExerciseItem_activityArrange arrange;
    private ExerciseItem_activityCommit commit;
    private ExerciseItem_activityDetails details;
    private ExerciseFragmentPagerAdapter adapter;
    private List<String>mTitles;
    private List<Fragment>mListFragment;
    private TabLayout mTablayout;
    private NoScrollViewPager mViewPager;
    private View mView;
    private Toolbar mToolbar;
    private TextView mTitle,item_exerciseitem2_title;
    private LinearLayout mLinearBanner;
    private String id,title;
    private String titles;
    private String type;
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        setTheme(R.style.AppTheme);
        super.onCreate(savedInstanceState);
        mView= LayoutInflater.from(this).inflate(R.layout.activity_exerciseitem2,null);
        setContentView(mView);
        ShareSDK.initSDK(this);
        Bundle bundle=getIntent().getBundleExtra("bundle");
        id=bundle.getString("id");
        type=bundle.getString("typed");
        titles=bundle.getString("title");
        initData();

        initFindView();
    }
    @Override
    public void initOnClck() {

    }
    private dialog_progress dialog_progress;
    private void setProgress(){
        dialog_progress=new dialog_progress(this);
        dialog_progress.requestWindowFeature(Window.FEATURE_NO_TITLE);

        dialog_progress.setCanceledOnTouchOutside(false);//按返回键可以关闭进度条
        dialog_progress.show();
    }


    @Override
    public void initFindView() {
        mToolbar= (Toolbar)findViewById(R.id.toolbar);
        mTitle= (TextView) findViewById(R.id.titles);

        //标题
        item_exerciseitem2_title= (TextView) findViewById(R.id.item_exerciseitem2_title);
        item_exerciseitem2_title.setText(titles);
        mTablayout= (TabLayout) mView.findViewById(R.id.item_exerciseitem2_tablayout);
        mViewPager= (NoScrollViewPager) mView.findViewById(R.id.item_exerciseitem2_viewpager);
        mTitle.setText("活动详情");
        mToolbar.setTitleTextColor(getResources().getColor(R.color.purple));
//        setSupportActionBar(mToolbar);
//        getSupportActionBar().setDisplayShowTitleEnabled(false);

        // 左上的图标按钮
        mToolbar.setNavigationIcon(R.mipmap.back3x);
        // 左上的图标按钮点击事件
        mToolbar.setNavigationOnClickListener(view -> {
            setFiish(this);
        });
        swipeRefreshLayout= (SwipeRefreshLayout) findViewById(R.id.swipe);
        swipeRefreshLayout.setEnabled(false);
        app_bar2= (AppBarLayout) findViewById(R.id.app_bar2);
        app_bar2.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                if (verticalOffset >= 0) {
                    swipeRefreshLayout.setEnabled(false);
                } else {
                    swipeRefreshLayout.setEnabled(false);
                }
            }
        });
        /**
         * 设置tablayout
         */
//        setTabLayout();
    }

    private Map<Object,Object>map;
    @Override
    public void initData() {
        setProgress();
        map=new HashMap<>();
        map.put("event_id",id);
        map.put("unique",SharePreceUtils.getOther("user","unique"));
        setRequest(MyUrl.url+MyUrl.events_detalis,map,handler,1);

    }
    private void setRequest(String url, Map<Object,Object>map,Handler handler,int tag){
        OkttpUtils.getIntence().OkttpPost(url,map,handler,tag);
    }
    /**
     * 设置轮播图
     */
    private List<String> images;
    private void setBanner(){
        mLinearBanner= (LinearLayout) findViewById(R.id.item_exerciseitem2_lineBanner);
        Banner banner= MyBanner.getIntence().init(mView, images, this);
        mLinearBanner.addView(banner);
        banner.setOnBannerClickListener((position)-> {

        });
    }
    /**
     * 设置tablayout
     */
    private Fragment fragment,fragment1,fragment2;
    private void setTabLayout(){
        mListFragment=new ArrayList<>();
        arrange=ExerciseItem_activityArrange.newInstance(webview);
        commit=ExerciseItem_activityCommit.newInstance(id);

        details=ExerciseItem_activityDetails.newInstance(activity.toString());

        mListFragment.add(details);
        mListFragment.add(arrange);
        mListFragment.add(commit);
        mTitles=new ArrayList<>();
        mTitles.add("活动须知");
        mTitles.add("活动安排");
        mTitles.add("活动评论");
        mTablayout.setTabMode(TabLayout.MODE_FIXED);
        adapter=new ExerciseFragmentPagerAdapter(getSupportFragmentManager(),mListFragment,mTitles);
        mViewPager.setAdapter(adapter);
        mTablayout.setupWithViewPager(mViewPager);
    }

    /**
     *解析数据
     */
    private String order_id;
    private String jsonString;
    private int code;
    private int typed;//id
    private int state;//状态
    private int buy_id;
    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            try{
                jsonString=msg.getData().getString("result");
                JSONObject object=new JSONObject(jsonString);
                code=object.getInt("code");
                if (code==100){
                    JSONObject result=object.getJSONObject("result");
                    if (msg.what==1){
                        typed=result.getInt("id");
                        price=result.getDouble("price");
                        JSONArray atlas=result.getJSONArray("atlas");
                        images=new ArrayList<>();
                        for (int i=0;i<atlas.length();i++){
                            images.add(atlas.getString(i));
                        }
                        /**
                         * 轮播图
                         */
                        setBanner();
                        JSONObject operation=result.getJSONObject("operation");
                        islike=operation.getInt("islike");//收藏
                        isapply=operation.getInt("isapply");//购买
                        setButtom();
                        activity=result.getJSONArray("activity");//活动须知
                        webview=result.getString("webview");//活动webview
                        workers=result.getJSONArray("workers");//活动评论
                        setTabLayout();//
                    }
                    else if(msg.what==2){
                        if (islike==0){//收藏
                            ToastUtils.setToast(object.getString("msg"),R.mipmap.activebottomlike3x,ExerciseItem2Activit.this);
                            Item_ExerciseItemButtom.initCollect(mView,(view1 )-> {

                            },1);
                            islike=1;
                        }
                        else {
                            ToastUtils.setToast(object.getString("msg"),R.mipmap.collect,ExerciseItem2Activit.this);
                            Item_ExerciseItemButtom.initCollect(mView,(view1 )-> {
                            },0);
                            islike=0;
                        }
                    }
                    /**
                     * 购买
                     */
                    else if (msg.what==3){
                        ToastUtils.setToastText(object.getString("extends"),ExerciseItem2Activit.this);
                        JSONObject events=result.getJSONObject("events");
                        int id=result.getInt("id");
                        buy_id=result.getInt("buy_id");
                        String typed=result.getString("typed");
                        order_id=result.getString("order_id");
                        SharePreceUtils.saveOrder(order_id,events.getString("title"),result.getString("price"));
                        Bundle bundle=new Bundle();
                        bundle.putString("order_id",order_id);
                        bundle.putString("events",result.getJSONObject("events").toString());
                        bundle.putString("typed",typed);
                        JumpIntents.startIntent(ExerciseItem2Activit.this,ReusingRaymentActivity.class,bundle);

                    }

                }

                else if(code==403){
                    ToastUtils.toast(object.getString("msg"));
                }
                if (dialog_progress.isShowing()){
                    dialog_progress.dismiss();
                }
            }
            catch (Exception e){
                e.printStackTrace();
            }
        }
    };

    private boolean isLogin=false;
    /**
     * 判断是否登录跳转登录界面
     */
    private void JumpLogin(){
        JumpIntents.startIntent(ExerciseItem2Activit.this,LoginAcitivity.class);

    }

    @Override
    protected void onResume() {
        super.onResume();
        isLogin=SharePreceUtils.getBoolean("user","isLogin");
    }
    /**
     * 设置底部分享等
     */
    private sharePopuWindow share;
    private void setButtom(){
        /**
         * 分享
         */
        AppBarLayout linearLayout= (AppBarLayout) findViewById(R.id.app_bar2);

        share=new sharePopuWindow(this,MyUrl.TYPE,typed+"");
        Item_ExerciseItemButtom.initShare(mView, (view)->{
                    share.showAsDropDown(mToolbar, Gravity.CENTER,0,0);

                }
        );
        /**
         * 收藏
         */
        Item_ExerciseItemButtom.initCollect(mView, new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
        },islike);
        Item_ExerciseItemButtom.textCollect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isLogin){
                    if (islike==0){
                        map=new HashMap<Object, Object>();
                        map.put("id",typed+"");
                        map.put("unique", SharePreceUtils.getOther("user","unique"));
                        map.put("typed",MyUrl.TYPE);
                        setRequest(MyUrl.COLLECT,map,handler,2);

                    }
                    else if (islike==1){//取消

                        map=new HashMap<Object, Object>();
                        map.put("id",typed+"");
                        map.put("unique", SharePreceUtils.getOther("user","unique"));
                        map.put("typed",MyUrl.TYPE);
                        setRequest(MyUrl.COLLECT,map,handler,2);

                    }
                }
                else {
                    JumpLogin();
                }

            }
        });



        /**
         * 购买
         * */

        OnClickLintener onClickLintener=new OnClickLintener();
        //弹窗
        popuWindowUtils=new PopPopuWindowUtils(this,onClickLintener,"查看报名凭证","取消报名",isapply);


        Item_ExerciseItemButtom.initBuy(mView,isapply,price);
        Item_ExerciseItemButtom.buyLinear.setOnClickListener((view1)->{
            if (isLogin){
                OnClickLintener paramOnClickListener = new OnClickLintener();
                if (isapply==1){
//                popuWindowUtils.showAsDropDown(linearLayout, Gravity.CENTER,0,0);
                }
                else if (isapply==0){
                        Bundle bundle=new Bundle();
                        bundle.putString("buy_id",typed+"");
                        bundle.putString("type",MyUrl.TYPE);
                        bundle.putString("order_id","");
                        JumpIntents.startIntent(ExerciseItem2Activit.this,ReusingRaymentActivity.class,bundle);//跳转到支付界面
                }
            }
            else {
                JumpLogin();
            }

        });
    }


    /**
     * popuwindow的弹框
     */
    class OnClickLintener implements View.OnClickListener{
        @Override
        public void onClick(View view) {
            switch (view.getId()){
                case R.id.popuwindow_examine:
                    break;
                case R.id.popuwindow_cancalenroll:
                    break;
                case R.id.popuwindow_cancal:
                    break;
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (dialog_progress!=null&&dialog_progress.isShowing()){
            dialog_progress.dismiss();
        }
    }
}
